package com.xinhe.web.service;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.CaseBuilder;
import com.querydsl.core.types.dsl.StringExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.QAssetDetail;
import com.xinhe.web.entity.QMember;
import com.xinhe.web.reposity.AssetDetailRepository;
import com.xinhe.web.response.AssetDetailByManagerView;
import com.xinhe.web.response.AssetDetailByUserView;
import com.xinhe.web.session.UserSessionManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AssetDetailCountService {

    @Autowired
    AssetDetailRepository assetDetailRepository;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<AssetDetailByUserView> pageAssetDetailByUser(String queryWord, String assetType, String assetType1, String tradeType, Date startTime, Date endTime,
                                                                     int pageNum, int pageSize) {
        QAssetDetail qAssetDetail = QAssetDetail.assetDetail;
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qAssetDetail.createTime.desc();
        builder.and(qAssetDetail.removed.eq(0));
        if (StringUtils.isNotEmpty(queryWord)) {
            builder.and(qMember.name.contains(queryWord).or(qMember.mobile.contains(queryWord)));
        }
        if (!Objects.isNull(assetType) && !Objects.isNull(assetType1)) {
            builder.and(qAssetDetail.assetType.eq(assetType).or(qAssetDetail.assetType.eq(assetType1)));
        } else if (!Objects.isNull(assetType)) {
            builder.and(qAssetDetail.assetType.eq(assetType));
        } else if (!Objects.isNull(assetType1)) {
            builder.and(qAssetDetail.assetType.eq(assetType1));
        }
        if (!Objects.isNull(tradeType)) {
            builder.and(qAssetDetail.tradeType.eq(tradeType));
        }
        if (!Objects.isNull(startTime) && !Objects.isNull(endTime)) {
            builder.and(qAssetDetail.createTime.between(startTime, endTime));
        }
        return queryFactory.select(
                        Projections.bean(
                                AssetDetailByUserView.class,
                                qAssetDetail.id,
                                qAssetDetail.assetType,
                                qAssetDetail.fUserId,
                                qAssetDetail.fBusinessId,
                                qAssetDetail.remainder,
                                //qAssetDetail.,
                                qMember.name,
                                qMember.mobile,
                                qAssetDetail.createTime,
                                qAssetDetail.tradeAmount,
                                qAssetDetail.tradeType
                        )
                ).from(qAssetDetail)
                .leftJoin(qMember).on(qAssetDetail.fUserId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetchResults();
    }
    @Autowired
    EntityManagerFactory entityManagerFactory;
    public QueryResults<AssetDetailByManagerView> pageAssetDetailByManager8(String queryWord, String assetType, String tradeType, Date startTime, Date endTime,
                                                                            int pageNum, int pageSize) {
        QAssetDetail qAssetDetail = QAssetDetail.assetDetail;
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qAssetDetail.createTime.desc();
        builder.and(qAssetDetail.removed.eq(0));
        if (StringUtils.isNotEmpty(queryWord)) {
            builder.and(qMember.name.contains(queryWord).or(qMember.mobile.contains(queryWord)));
        }
        if (!Objects.isNull(startTime) && !Objects.isNull(endTime)) {
            builder.and(qAssetDetail.createTime.between(startTime, endTime));
        }
//对类型字段进行映射，如资产类型
        StringExpression assetTypeStr = new CaseBuilder()
                .when(qAssetDetail.assetType.eq("RMB")).then("人民币")
                .when(qAssetDetail.assetType.eq("YUN_CHA_SEED")).then("云茶籽")
                .when(qAssetDetail.assetType.eq("NEW_YUN_CHA_SEED")).then("新云茶籽")
                .when(qAssetDetail.assetType.eq("TEA_OIL_CARD")).then("茶油卡")
                .when(qAssetDetail.assetType.eq("UNFREEZING_CONSUMER_GOLD_RED_ENVELOPE")).then("解冻消费金红包")
                .when(qAssetDetail.assetType.eq("TEA_OIL")).then("茶油")
                .otherwise("未知");
        StringExpression tradeTypeStr = new CaseBuilder()
                .when(qAssetDetail.tradeType.eq("USER_WITHDRAWAL")).then("用户提现")
                .when(qAssetDetail.tradeType.eq("PARTNER_DIVIDENDS")).then("合伙人分红")
                .when(qAssetDetail.tradeType.eq("STUDIO_DIVIDENDS")).then("工作室分红")
                .when(qAssetDetail.tradeType.eq("FOUNDER_DIVIDENDS")).then("创始人分红")
                .when(qAssetDetail.tradeType.eq("MANAGEMENT_ALLOWANCE")).then("管理津贴")
                .when(qAssetDetail.tradeType.eq("FARMER_DIVIDENDS")).then("农场主分红")
                .when(qAssetDetail.tradeType.eq("XINHE_REWARD")).then("芯禾奖励")
                .when(qAssetDetail.tradeType.eq("SELLER_WITHDRAWAL")).then("商家提现")
                .when(qAssetDetail.tradeType.eq("SYSTEM_WITHDRAWAL")).then("系统自动提现")
                .when(qAssetDetail.tradeType.eq("COMPANY_WITHDRAWAL")).then("公司扣缴")
                .when(qAssetDetail.tradeType.eq("USER_WITHDRAWAL_REJECT")).then("提现拒绝")
                .when(qAssetDetail.tradeType.eq("USER_EXCHANGE_REJECT")).then("兑换茶油卡拒绝")
                .when(qAssetDetail.tradeType.eq("WEIXIN_RMB_RECHARGE")).then("微信充值")
                .when(qAssetDetail.tradeType.eq("ADOPTING_OIL_TEA_TREES")).then("认养油茶树")
                .when(qAssetDetail.tradeType.eq("ADOPTED_TREE")).then("认养油茶树赠送")
                .when(qAssetDetail.tradeType.eq("ADDITIONAL_GIFT_YUN_CHA_SEED")).then("额外赠送云茶籽")
                .when(qAssetDetail.tradeType.eq("ADOPTED_OIL_CARD")).then("认养油茶树赠送")
                .when(qAssetDetail.tradeType.eq("ADOPTED_OIL_CARD_EXCHANGE_TEA_OIL")).then("兑换茶油")
                .when(qAssetDetail.tradeType.eq("SYSTEM_THAW_YUN_CHA_SEED")).then("系统解冻")
                .when(qAssetDetail.tradeType.eq("SYSTEM_THAW_CONSUMER_GOLD_RED_ENVELOPE")).then("系统自动领取")
                .when(qAssetDetail.tradeType.eq("TWO_THAW_YUN_CHA_SEED")).then("认养油茶树赠送")
                .when(qAssetDetail.tradeType.eq("ADOPTED_TREE")).then("直推解冻云茶籽")
                .when(qAssetDetail.tradeType.eq("THREE_THAW_YUN_CHA_SEED")).then("间推解冻云茶籽")
                .when(qAssetDetail.tradeType.eq("TWO_THAW_REWARD")).then("直推奖励")
                .when(qAssetDetail.tradeType.eq("THREE_THAW_REWARD")).then("间推奖励")
                .when(qAssetDetail.tradeType.eq("ADDITIONAL_REWARDS")).then("额外奖励")
                .when(qAssetDetail.tradeType.eq("FOUNDER_REWARDS")).then("推荐创始人获得奖励")
                .when(qAssetDetail.tradeType.eq("RECOMMEND_FOUNDER_THAWING")).then("推荐创始人解冻云茶籽")
                .when(qAssetDetail.tradeType.eq("ADDITIONAL_YUN_CHA_SEED")).then("额外解冻云茶籽")
                .when(qAssetDetail.tradeType.eq("EXCHANGE_ZONE_GOODS")).then("兑换专区商品")
                .when(qAssetDetail.tradeType.eq("BUY_ZONE_GOODS")).then("购买专区商品")
                .when(qAssetDetail.tradeType.eq("SELLER_ORDER_COLLECTION")).then("商家订单收入")
                .when(qAssetDetail.tradeType.eq("BUYER_ORDER_PAY")).then("买家订单支付")
                .when(qAssetDetail.tradeType.eq("BUYER_ORDER_RETURN")).then("订单退款")
                .when(qAssetDetail.tradeType.eq("REVENUE_SELLING_GOODS")).then("销售商品收益")
                .otherwise("未知");
        QueryResults<AssetDetailByManagerView> assetDetailByManagerViewQueryResults = queryFactory.select(
                        Projections.bean(
                                AssetDetailByManagerView.class,
                                qMember.name,
                                qMember.mobile,
                                qAssetDetail.id,
                                qAssetDetail.fUserId,
                                qAssetDetail.fBusinessId,
                                qAssetDetail.assetType,
                                qAssetDetail.remainder,
                                qAssetDetail.createTime,
                                qAssetDetail.tradeAmount,
                                qAssetDetail.tradeType,
                                assetTypeStr.as("assetTypeStr"),
                                tradeTypeStr.as("tradeTypeStr")
                        )
                ).from(qAssetDetail)
                .leftJoin(qMember).on(qAssetDetail.fUserId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetchResults();
        List<AssetDetailByManagerView> results = assetDetailByManagerViewQueryResults.getResults();
        // 创建一个用于存储修改后元组对象的列表
        List<AssetDetailByManagerView> modifiedResults = new ArrayList<>();
        // 遍历分页记录，进行字段值重新赋值
        for (AssetDetailByManagerView assetDetailByManagerView : results) {
            //查询sumTeaOilCard
            BigDecimal sumTeaOilCard = assetDetailRepository.sumTeaOilCard(assetDetailByManagerView.getfUserId());
            //查询sumConsumerGoldRedEnvelope
            BigDecimal sumConsumerGoldRedEnvelope = assetDetailRepository.sumConsumerGoldRedEnvelope(assetDetailByManagerView.getfUserId());
            //查询sumYunChaSeed
            BigDecimal sumYunChaSeed = assetDetailRepository.sumYunChaSeed(assetDetailByManagerView.getfUserId());
            // 创建一个新的元组对象，并将修改后的字段值设置到新的元组对象中
            AssetDetailByManagerView newAssetDetail = new AssetDetailByManagerView();
            BeanUtils.copyProperties(assetDetailByManagerView, newAssetDetail);
            newAssetDetail.setSumTeaOilCard(sumTeaOilCard);
            newAssetDetail.setSumConsumerGoldRedEnvelope(sumConsumerGoldRedEnvelope);
            newAssetDetail.setSumYunChaSeed(sumYunChaSeed);
            // 将修改后的元组对象添加到列表中
            modifiedResults.add(newAssetDetail);
        }
        // 创建一个新的QueryResults对象，包含修改后的分页记录
        QueryResults<AssetDetailByManagerView> modifiedQueryResults = new QueryResults<>(
                modifiedResults,
                assetDetailByManagerViewQueryResults.getTotal(),
                assetDetailByManagerViewQueryResults.getOffset(),
                assetDetailByManagerViewQueryResults.getLimit()
        );
        return modifiedQueryResults;
    }

    public QueryResults<AssetDetailByManagerView> pageAssetDetailByManager(String queryWord, String assetType,String assetType1, String tradeType, Date startTime, Date endTime,
                                                                           int pageNum, int pageSize) {
        QAssetDetail qAssetDetail = QAssetDetail.assetDetail;
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qAssetDetail.createTime.desc();
        builder.and(qAssetDetail.removed.eq(0));
        if (StringUtils.isNotEmpty(queryWord)) {
            builder.and(qMember.name.contains(queryWord).or(qMember.mobile.contains(queryWord)));
        }
        if (!Objects.isNull(assetType) && !Objects.isNull(assetType1)) {
            builder.and(qAssetDetail.assetType.eq(assetType).or(qAssetDetail.assetType.eq(assetType1)));
        } else if (!Objects.isNull(assetType)) {
            builder.and(qAssetDetail.assetType.eq(assetType));
        } else if (!Objects.isNull(assetType1)) {
            builder.and(qAssetDetail.assetType.eq(assetType1));
        }
        /*if (!Objects.isNull(assetType)) {
            builder.and(qAssetDetail.assetType.eq(assetType));
        }
        if (!Objects.isNull(assetType1)) {
            builder.and(qAssetDetail.assetType.eq(assetType1));
        }*/
        if (!Objects.isNull(tradeType)) {
            builder.and(qAssetDetail.tradeType.eq(tradeType));
        }
        if (!Objects.isNull(startTime) && !Objects.isNull(endTime)) {
            builder.and(qAssetDetail.createTime.between(startTime, endTime));
        }
        //对类型字段进行映射，如资产类型
        StringExpression assetTypeStr = new CaseBuilder()
                .when(qAssetDetail.assetType.eq("RMB")).then("人民币")
                .when(qAssetDetail.assetType.eq("YUN_CHA_SEED")).then("云茶籽")
                .when(qAssetDetail.assetType.eq("NEW_YUN_CHA_SEED")).then("新云茶籽")
                .when(qAssetDetail.assetType.eq("TEA_OIL_CARD")).then("茶油卡")
                .when(qAssetDetail.assetType.eq("UNFREEZING_CONSUMER_GOLD_RED_ENVELOPE")).then("解冻消费金红包")
                .when(qAssetDetail.assetType.eq("TEA_OIL")).then("茶油")
                .otherwise("未知");
        StringExpression tradeTypeStr = new CaseBuilder()
                .when(qAssetDetail.tradeType.eq("USER_WITHDRAWAL")).then("用户提现")
                .when(qAssetDetail.tradeType.eq("PARTNER_DIVIDENDS")).then("合伙人分红")
                .when(qAssetDetail.tradeType.eq("STUDIO_DIVIDENDS")).then("工作室分红")
                .when(qAssetDetail.tradeType.eq("FOUNDER_DIVIDENDS")).then("创始人分红")
                .when(qAssetDetail.tradeType.eq("MANAGEMENT_ALLOWANCE")).then("管理津贴")
                .when(qAssetDetail.tradeType.eq("FARMER_DIVIDENDS")).then("农场主分红")
                .when(qAssetDetail.tradeType.eq("XINHE_REWARD")).then("芯禾奖励")
                .when(qAssetDetail.tradeType.eq("SELLER_WITHDRAWAL")).then("商家提现")
                .when(qAssetDetail.tradeType.eq("SYSTEM_WITHDRAWAL")).then("系统自动提现")
                .when(qAssetDetail.tradeType.eq("COMPANY_WITHDRAWAL")).then("公司扣缴")
                .when(qAssetDetail.tradeType.eq("USER_WITHDRAWAL_REJECT")).then("提现拒绝")
                .when(qAssetDetail.tradeType.eq("USER_EXCHANGE_REJECT")).then("兑换茶油卡拒绝")
                .when(qAssetDetail.tradeType.eq("WEIXIN_RMB_RECHARGE")).then("微信充值")
                .when(qAssetDetail.tradeType.eq("ADOPTING_OIL_TEA_TREES")).then("认养油茶树")
                .when(qAssetDetail.tradeType.eq("ADOPTED_TREE")).then("认养油茶树赠送")
                .when(qAssetDetail.tradeType.eq("ADDITIONAL_GIFT_YUN_CHA_SEED")).then("额外赠送云茶籽")
                .when(qAssetDetail.tradeType.eq("ADOPTED_OIL_CARD")).then("认养油茶树赠送")
                .when(qAssetDetail.tradeType.eq("ADOPTED_OIL_CARD_EXCHANGE_TEA_OIL")).then("兑换茶油")
                .when(qAssetDetail.tradeType.eq("SYSTEM_THAW_YUN_CHA_SEED")).then("系统解冻")
                .when(qAssetDetail.tradeType.eq("SYSTEM_THAW_CONSUMER_GOLD_RED_ENVELOPE")).then("系统自动领取")
                .when(qAssetDetail.tradeType.eq("TWO_THAW_YUN_CHA_SEED")).then("认养油茶树赠送")
                .when(qAssetDetail.tradeType.eq("ADOPTED_TREE")).then("直推解冻云茶籽")
                .when(qAssetDetail.tradeType.eq("THREE_THAW_YUN_CHA_SEED")).then("间推解冻云茶籽")
                .when(qAssetDetail.tradeType.eq("TWO_THAW_REWARD")).then("直推奖励")
                .when(qAssetDetail.tradeType.eq("THREE_THAW_REWARD")).then("间推奖励")
                .when(qAssetDetail.tradeType.eq("ADDITIONAL_REWARDS")).then("额外奖励")
                .when(qAssetDetail.tradeType.eq("FOUNDER_REWARDS")).then("推荐创始人获得奖励")
                .when(qAssetDetail.tradeType.eq("RECOMMEND_FOUNDER_THAWING")).then("推荐创始人解冻云茶籽")
                .when(qAssetDetail.tradeType.eq("ADDITIONAL_YUN_CHA_SEED")).then("额外解冻云茶籽")
                .when(qAssetDetail.tradeType.eq("EXCHANGE_ZONE_GOODS")).then("兑换专区商品")
                .when(qAssetDetail.tradeType.eq("BUY_ZONE_GOODS")).then("购买专区商品")
                .when(qAssetDetail.tradeType.eq("SELLER_ORDER_COLLECTION")).then("商家订单收入")
                .when(qAssetDetail.tradeType.eq("BUYER_ORDER_PAY")).then("买家订单支付")
                .when(qAssetDetail.tradeType.eq("BUYER_ORDER_RETURN")).then("订单退款")
                .when(qAssetDetail.tradeType.eq("REVENUE_SELLING_GOODS")).then("销售商品收益")
                .otherwise("未知");
        QueryResults<AssetDetailByManagerView> assetDetailByManagerViewQueryResults = queryFactory.select(
                        Projections.bean(
                                AssetDetailByManagerView.class,
                                qMember.name,
                                qMember.mobile,
                                qAssetDetail.id,
                                qAssetDetail.fUserId,
                                qAssetDetail.fBusinessId,
                                qAssetDetail.assetType,
                                qAssetDetail.remainder,
                                qAssetDetail.createTime,
                                qAssetDetail.tradeAmount,
                                qAssetDetail.tradeType,
                                assetTypeStr.as("assetTypeStr"),
                                tradeTypeStr.as("tradeTypeStr")
                        )
                ).from(qAssetDetail)
                .leftJoin(qMember).on(qAssetDetail.fUserId.eq(qMember.fUserId).and(qMember.removed.eq(0)))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetchResults();
        List<AssetDetailByManagerView> results = assetDetailByManagerViewQueryResults.getResults();
        // 创建一个用于存储修改后元组对象的列表
        List<AssetDetailByManagerView> modifiedResults = new ArrayList<>();
        // 遍历分页记录，进行字段值重新赋值
        for (AssetDetailByManagerView assetDetailByManagerView : results) {
            //查询sumTeaOilCard
            BigDecimal sumTeaOilCard = assetDetailRepository.sumTeaOilCard(assetDetailByManagerView.getfUserId());
            //查询sumConsumerGoldRedEnvelope
            BigDecimal sumConsumerGoldRedEnvelope = assetDetailRepository.sumConsumerGoldRedEnvelope(assetDetailByManagerView.getfUserId());
            //查询sumYunChaSeed
            BigDecimal sumYunChaSeed = assetDetailRepository.sumYunChaSeed(assetDetailByManagerView.getfUserId());
            // 创建一个新的元组对象，并将修改后的字段值设置到新的元组对象中
            AssetDetailByManagerView newAssetDetail = new AssetDetailByManagerView();
            BeanUtils.copyProperties(assetDetailByManagerView, newAssetDetail);
            newAssetDetail.setSumTeaOilCard(sumTeaOilCard);
            newAssetDetail.setSumConsumerGoldRedEnvelope(sumConsumerGoldRedEnvelope);
            newAssetDetail.setSumYunChaSeed(sumYunChaSeed);
            // 将修改后的元组对象添加到列表中
            modifiedResults.add(newAssetDetail);
        }
        // 创建一个新的QueryResults对象，包含修改后的分页记录
        QueryResults<AssetDetailByManagerView> modifiedQueryResults = new QueryResults<>(
                modifiedResults,
                assetDetailByManagerViewQueryResults.getTotal(),
                assetDetailByManagerViewQueryResults.getOffset(),
                assetDetailByManagerViewQueryResults.getLimit()
        );
        return modifiedQueryResults;
    }
    @Autowired
    private UserSessionManager userSessionManager;
    public Result findByYunChaSend() {
        Long userId = this.userSessionManager.getUserId();
        BigDecimal yunChaSend = this.assetDetailRepository.findByYunChaSend(userId);
        return Result.ok(yunChaSend);
    }

    public Result findByTeaOil() {
        Long userId = this.userSessionManager.getUserId();
        BigDecimal teaOil = this.assetDetailRepository.findByTeaOil(userId);
        return Result.ok(teaOil);
    }

    public Result findByTeaOilCard() {
        Long userId = this.userSessionManager.getUserId();
        BigDecimal teaOilCard = this.assetDetailRepository.findByTeaOilCard(userId);
        return Result.ok(teaOilCard);
    }

}
